<template>
	<view class="empytView" v-if="!conversationList.length || !db.get('auth')">
		<image :src="'/images/kong.png' | formatImgUrl" mode="widthFix" />
	</view>
  <div class="tui-conversation-list" v-else>
    <ActionsMenu
      v-if="isShowOverlay"
      :selectedConversation="currentConversation"
      :actionsMenuPosition="actionsMenuPosition"
      :selectedConversationDomRect="currentConversationDomRect"
      @closeConversationActionMenu="closeConversationActionMenu"
    />
    <div
      v-for="(conversation, index) in conversationList"
      :id="`convlistitem-${index}`"
      :key="index"
      :class="[
        'TUI-conversation-content',
        !isPC && 'TUI-conversation-content-h5',
      ]"
	  v-if="conversation._conversation.lastMessage.messageForShow && conversation.conversationID != 'C2Cwritermsg'"
    >
      <div
        @click="enterConversationChat(conversation)"
        @longpress="showConversationActionMenu($event, conversation, index)"
        @contextmenu.prevent="showConversationActionMenu($event, conversation, index, true)"
        :class="[
          isPC && 'isPC',
          'TUI-conversation-item',
          currentConversationID === conversation.conversationID &&
            'TUI-conversation-item-selected',
          conversation.isPinned && 'TUI-conversation-item-pinned',
        ]"
      >
        <aside class="left">
			<block v-if="conversation.conversationID == 'C2Chudongmsg' || conversation.conversationID == 'C2Csysmsg' || conversation.conversationID == 'C2Cadministrator' || conversation.conversationID == 'C2Cwritermsg'">
				<img class="avatar" :src="conversation.pic || conversation.getAvatar()" />
			</block>
			<block v-else>
				<img class="avatar" :class="conversation.is_line == 1 ? '' : 'gray'" :src="conversation.pic || conversation.getAvatar()" />
			</block>
		  
          <div
            v-if="userOnlineStatusMap && isShowUserOnlineStatus(conversation)"
            :class="[
              'online-status',
              Object.keys(userOnlineStatusMap).length > 0 &&
              Object.keys(userOnlineStatusMap).includes(
                conversation.userProfile.userID
              ) &&
              userOnlineStatusMap[conversation.userProfile.userID]
                .statusType === 1
                ? 'online-status-online'
                : 'online-status-offline',
            ]"
          ></div>
          <span
            class="num"
            v-if="conversation.unreadCount > 0 && !conversation.isMuted"
          >
            {{
              conversation.unreadCount > 99 ? "99+" : conversation.unreadCount
            }}
          </span>
          <span
            class="num-notify"
            v-if="conversation.unreadCount > 0 && conversation.isMuted"
          ></span>
        </aside>
        <div class="content" style="padding-bottom: 0!important;">
          <div class="content-header">
            <label class="content-header-label display-flex">
				<!-- <block v-if="conversation.conversationID == 'C2Chudongmsg' || conversation.conversationID == 'C2Csysmsg' || conversation.conversationID == 'C2Cadministrator' || conversation.conversationID == 'C2Cwritermsg'">
					<p class="name">{{ conversation.getShowName() }}</p>
				</block>
				<block v-else>
					<p class="name">{{ conversation.nickname || conversation.getShowName() }}</p>
				</block> -->
              <p class="name">{{ conversation.getShowName() }}</p>
			  <span v-if="conversation.isPinned" class="isPinned">置顶</span>
            </label>
            <div class="middle-box">
              <span
                class="middle-box-at"
                v-if="
                  conversation.type === 'GROUP' &&
                  conversation.groupAtInfoList &&
                  conversation.groupAtInfoList.length > 0
                "
                >{{ conversation.getGroupAtInfo() }}</span
              >
              <p class="middle-box-content">
                {{ conversation.lastMsg || conversation.getLastMessage("text") }}
              </p>
            </div>
          </div>
          <div class="content-footer">
			  <!-- <Icon v-if="conversation.isMuted" :file="muteIcon"></Icon> -->
			
			<div class="display-flex" v-if="conversation.conversationID != 'C2Chudongmsg' && conversation.conversationID != 'C2Cadministrator' && conversation.conversationID != 'C2Csysmsg' && conversation.conversationID != 'C2Cwritermsg'">
				<!-- <image v-if="conversation.writer_level&&conversation.writer_level.is_active"
					:src="$options.filters.formatImgUrlNew(conversation.writer_level&&conversation.writer_level.is_active?conversation.writer_level&&conversation.writer_level.level&&conversation.writer_level.level.image:conversation.writer_level&&conversation.writer_level.level&&conversation.writer_level.level.hide_img)"
					@click.stop="$go('/pages/user/grade?uid='+conversation.membe_id)"
					class="jipic" mode=""
					>
				</image>
				<image
					:src="$options.filters.formatImgUrlNew(conversation.user_level&&conversation.user_level.is_active?conversation.user_level&&conversation.user_level.level&&conversation.user_level.level.image:conversation.user_level&&conversation.user_level.level&&conversation.user_level.level.hide_img)"
					class="biepic" mode=""
					v-if="conversation.user_level&&conversation.user_level.is_active">
				</image> -->
			</div>
            <span class="time">{{ conversation.getLastMessage("time") }}</span>
            
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
interface IUserStatus {
  statusType: number;
  customStatus: string;
}

interface IUserStatusMap {
  [userID: string]: IUserStatus;
}

import * as db from '@/common/db.js'

import { ref } from "../../../adapter-vue";
import TUIChatEngine, {
  TUIGlobal,
  TUIStore,
  StoreName,
  TUIConversationService,
} from "@tencentcloud/chat-uikit-engine";
import { IConversationModel } from "@tencentcloud/chat-uikit-engine";
import Icon from "../../common/Icon.vue";
import ActionsMenu from "../actions-menu/index.vue";
import muteIcon from "../../../assets/icon/mute.svg";
import { isUniFrameWork } from "../../../utils/is-uni";

const emits = defineEmits(["handleSwitchConversation", "getPassingRef"]);
const isH5 = TUIGlobal.getPlatform() === "h5";
const isPC = ref(TUIGlobal.getPlatform() === "pc");
const currentConversation = ref<typeof IConversationModel>();
const currentConversationID = ref<string>();
const currentConversationDomRect = ref<DOMRect>();
const isShowOverlay = ref<boolean>(false);
const conversationList = ref<typeof IConversationModel[]>([]);
const conversationListDomRef = ref<HTMLElement | undefined>();
const actionsMenuPosition = ref<{top: number, left?: number, conversationHeight?: number}>({
  top: 0,
});
const displayOnlineStatus = ref(false); // 在线状态 默认关闭
const userOnlineStatusMap = ref<IUserStatusMap>();

let lastestOpenActionsMenuTime: number | null = null;


TUIStore.watch(StoreName.CONV, {
  currentConversationID: (id: string) => {
    currentConversationID.value = id;
  },
  conversationList: (list: Array<typeof IConversationModel>) => {
	for(let i in list){
		let item = list[i]
		
		if(item.conversationID != 'C2Chudongmsg' && item.conversationID != 'C2Cadministrator' && item.conversationID != 'C2Csysmsg' && item.conversationID != 'C2Cwritermsg'){
			uni.request({
			    url: 'https://api.dreamyuewen.com/api/index/getMsgList', 
			    data: {
			       ids_arr: [item.userProfile.userID],
			    },
				method: 'POST',
			    header: {
			        token: db.get('auth')
			    },
			    success: (resss) => {
					var result = resss.data && resss.data.data && resss.data.data.data && resss.data.data.data[0]
					item.user_level = result.user_level
					item.writer_level = result.writer_level
					item.pic = result.pic
					item.is_line = result.is_line
					
					item.is_vip = result.is_vip
					item.is_writer = result.is_writer
					item.membe_id = result.membe_id
					item.nickname = result.nickname
			    }
			});  
		}else{
			let msg =item.lastMessage.messageForShow
			
			if (msg && msg.indexOf('type') > -1) {
				let msgParse = JSON.parse(msg.substr(4))
				item.lastMsg = msgParse.title
			}
		}
		
	}
	
    conversationList.value = list;
  },
  currentConversation: (conversation: typeof IConversationModel) => {
    currentConversation.value = conversation;
  },
});

const updatelist= ()=>{
	console.log('updatelist',111);
	let list = conversationList.value
	for(let i in list){
		let item = list[i]
		
		if(item.conversationID != 'C2Chudongmsg' && item.conversationID != 'C2Cadministrator' && item.conversationID != 'C2Csysmsg' && item.conversationID != 'C2Cwritermsg')
		uni.request({
		    url: 'https://api.dreamyuewen.com/api/index/getMsgList', 
		    data: {
		       ids_arr: [item.userProfile.userID],
		    },
			method: 'POST',
		    header: {
		        token: db.get('auth')
		    },
		    success: (resss) => {
				var result = resss.data && resss.data.data && resss.data.data.data && resss.data.data.data[0]
				item.user_level = result.user_level
				item.writer_level = result.writer_level
				item.pic = result.pic
				item.is_line = result.is_line
				
				item.is_vip = result.is_vip
				item.is_writer = result.is_writer
				item.membe_id = result.membe_id
				item.nickname = result.nickname
		    }
		});  
	}
	
	conversationList.value = list;
	console.log(list);
}

// 初始状态
TUIStore.watch(StoreName.USER, {
  displayOnlineStatus: (status: boolean) => {
    displayOnlineStatus.value = status;
  },
  userStatusList: (list: Map<string, IUserStatus>) => {
    if (list.size !== 0) {
      userOnlineStatusMap.value = [...list.entries()].reduce(
        (obj, [key, value]) => {
          obj[key] = value;
          return obj;
        },
        {} as IUserStatusMap
      );
    }
  },
});

const isShowUserOnlineStatus = (conversation: typeof IConversationModel): boolean => {
  return (
    displayOnlineStatus.value &&
    conversation.type === TUIChatEngine.TYPES.CONV_C2C
  );
};

const showConversationActionMenu = (
  event: Event,
  conversation: typeof IConversationModel,
  index: number,
  isContextMenuEvent?: boolean
) => {
  if (isContextMenuEvent && isUniFrameWork) {
    return;
  }
  currentConversation.value = conversation;
  lastestOpenActionsMenuTime = Date.now();
  getActionsMenuPosition(event, index);
};

const closeConversationActionMenu = () => {
  // 防止连续触发overlay的tap事件
  if (
    lastestOpenActionsMenuTime &&
    Date.now() - lastestOpenActionsMenuTime > 300
  ) {
    currentConversation.value = undefined;
    isShowOverlay.value = false;
  }
};

const getActionsMenuPosition = (event: Event, index: number, conversation?: any) => {
  if (isUniFrameWork) {
    if (typeof conversationListDomRef.value === 'undefined') {
      emits('getPassingRef', conversationListDomRef);
    }
    const query = uni.createSelectorQuery().in(conversationListDomRef.value);
    query.select(`#convlistitem-${index}`).boundingClientRect(data => {
      if (data) {
        actionsMenuPosition.value = {
          // uni-h5的uni-page-head不被认为是视窗中的成员，因此手动上head的高度
          top: data.bottom + (isH5 ? 44 : 0),
          left: event.touches[0].pageX,
          conversationHeight: data.height,
        };
        isShowOverlay.value = true;
      }
    }).exec();
  } else {
    // 处理Vue原生
    const rect = event.currentTarget?.getBoundingClientRect();
    if (rect) {
      actionsMenuPosition.value = {
        top: rect.bottom,
        left: isPC.value ? event.clientX : undefined,
        conversationHeight: rect.height,
      };
    }
    isShowOverlay.value = true;
  }
};


let isClick = true;
const enterConversationChat = (item: string) => {
	console.log(isClick);
	if(!isClick){
		return
	}
	isClick = false
	uni.setStorageSync("userProfile",item.userProfile);
	
	uni.request({
	    url: 'https://api.dreamyuewen.com/api/user/userInfo', 
	    data: {
	       uid: item.userProfile.userID,
	    },
	    header: {
	        token: db.get('auth')
	    },
	    success: (res) => {
	        uni.setStorageSync("userItem",res.data.user);
			
			uni.request({
			    url: 'https://api.dreamyuewen.com/api/user/userPageList', 
			    data: {
			       uid: item.userProfile.userID,
				   page: 1,
				   type: 1
			    },
			    header: {
			        token: db.get('auth')
			    },
			    success: (ress) => {
			        uni.setStorageSync("userPageList",ress.data.data.data);
					
					uni.request({
					    url: 'https://api.dreamyuewen.com/api/order/getTimOrderList', 
					    data: {
					       uid: item.userProfile.userID,
					    },
					    header: {
					        token: db.get('auth')
					    },
					    success: (resss) => {
							setTimeout(()=> {
								isClick = true
							}, 2000);
					        uni.setStorageSync("orderList",resss.data.data);
							
							emits("handleSwitchConversation", item.conversationID);
							TUIConversationService.switchConversation(item.conversationID);
					    }
					});
			    }
			});
	    }
	});
	
	
	
	
	
	
	
  // emits("handleSwitchConversation", item.conversationID);
  // TUIConversationService.switchConversation(item.conversationID);
};

// 暴露给父组件，当监听到滑动事件时关闭actionsMenu
defineExpose({ closeChildren: closeConversationActionMenu, updatelist: updatelist});
</script>

<style lang="scss" scoped src="./style/index.scss"></style>
<style lang="scss" scoped>
	.jipic {
		width: 41px;
		height:19px;
		margin-left: 4px;
	}
	
	.biepic {
		width: 41px;
		height:19px;
		margin-left: 4px;
	}
	
	.avatar.gray{
		filter: grayscale(.8)
	}
	
	.isPinned{
		background: rgba(#45C4B0, .15);
		color: #45C4B0;
		font-size: 20rpx;
		width: 37px;
		height: 16px;
		text-align: center;
		line-height: 16px;
		border-radius: 4px;
		margin-left: 3px;
	}
</style>
